<?php

namespace App\Services;

use Auth;

class AuthService extends Service
{
    protected $guard = '';

    public function setGuard($guard)
    {
        $this->guard = $guard;
    }

    public function refreshToken()
    {
        $token = Auth::guard($this->guard)->refresh();
        return $this->respondWithToken($token, 204);
    }

    public function deleteToken()
    {
        Auth::guard($this->guard)->logout();
        return $this->noContent();
    }

    public function respondWithToken($token, $code = 200)
    {
        $result = [
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => Auth::guard($this->guard)->factory()->getTTL() * 60
        ];
        return $this->success($result, $code);
    }

    public function login($userName, $password)
    {
        $this->isMobile($userName) ?
            $credentials['phone'] = $userName :
            $credentials['name'] = $userName;
        $credentials['password'] = $password;
        if (!$token = Auth::guard($this->guard)->attempt($credentials)) {
            return $this->failed('账号验证未通过', 401);
        }
        return $this->respondWithToken($token);
    }

    function isMobile($mobile)
    {
        if (!is_numeric($mobile)) {
            return false;
        }
        return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $mobile) ? true : false;
    }
}